import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores'

import { useRouter } from 'vue-router'

const router = useRouter()
const IMAGE_URL = 'http://localhost:8081'

// 创建axios实例
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_API_BASEURL,
  timeout: 50000
})

service.defaults.withCredentials = true

// 请求拦截器
service.interceptors.request.use(
  config => {
    const userStore = useUserStore() 
    if (userStore.token) {
      config.headers['Authorization'] = `${userStore.token}`
    }
    return config
  },
  error => {
    console.error('Request error:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    const userStore = useUserStore()
    // 如果返回的状态码不是200，说明接口请求失败
    if (res.code !== 200) {
      ElMessage({
        message: res.msg || 'Error',
        type: 'error',
        duration: 5 * 1000
      })

      // 401: 未登录或token过期
      if (res.code === 401 || res.code === 405) {
        // 清除token并跳转到登录页
        userStore.logout()
        router.push('/login')
      }
      return Promise.reject(new Error(res.msg || 'Error'))
    } else {
      return res
    }
  },
  error => {
    console.error('Response error:', error)
    ElMessage({
      message: error.msg || '请求失败',
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)
export default service

export {
  IMAGE_URL
}